import React from 'react';
import {Form, Input, Button, Select, Table, Card, Modal, InputNumber,  Popover, Pagination, Message, Icon, DatePicker, Row, Col  } from 'antd';
import BatchChargingModal from './batchChargingModal';
const FormItem = Form.Item;

let List = React.createClass({

  getInitialState() {
    return {
      loading: false,
      visible: false,
      data: [],
      roomId: '',
      dataBox: null,
      setData: {},
      ids: [],
      page: {
        total: 0,
        current: 1,
        pageSize: 5
      },
      startValue:null, //抄表开始时间
    }
  },

  componentDidMount() {
    this.handleSearch();
  },

  fetch() {
    let forms = this.props.form.getFieldsValue();
    let page = this.state.page.current;
    let params = Object.assign({}, {pageSize: 5, currentPage: page}, forms);
    let _me = this;

    Utils.sendAjax({
      url: '/rent/batchMeter/list',
      data: JSON.stringify(params),
      callback: function(result) {
        if (result.code == '200') {
          _me.setState({
            data: result.data,
            dataBox: _me.itemRender(result.data),
            page: {
              total: result.page.total,
              pageSize: 5,
              current: result.page.currentPage,
            }
          })
        } else {
          Message.error(result.message, 10)
        }
      }
    })
  },



  handlePageChange(page) {
    let pager = this.state.page;
    pager.current = page;
    this.setState({
      pagination: {
        current: pager
      }
    })
    this.handleSearch();
  },

  handleSearch() {
    this.fetch();
  },

  handleReset() {
    this.props.form.resetFields();
  },

  handleFiled(filed, val) {
    let newStr = this.state.setData;
    let newIds = this.state.ids;
    let k = filed.key ? filed.key.split('-')[2] : filed.split('-')[2];
    let name = filed.key ? filed.name : filed;
    let value = filed.key ? val : Utils.formatDate(val);
    newStr[name] = value;
    if (filed.key) {
      newStr[filed.key] = filed[filed.key]
    }
 
    newIds.push(k)
    this.setState({
      setData: newStr,
      ids: newIds,
      startValue: value 
    })
  },

  // 结束时间disabled
  disabledEndDate(endValue) {
    
     return endValue.getTime() <= (new Date(new Date().getTime()-24*60*60*1000));
  },

  handleSubmit() {
    
    let roomList = this.setFieldArr(this.state.setData);
    let forms = {};
    let isEmpty = true; // 为空
    if(roomList){
      roomList.forEach((item)=> {
        if(item.meterList.length > 0){
          isEmpty = false;
        }
      })
    }

    if(isEmpty == false){          
        forms = {roomList: roomList};
        let params = Object.assign({}, forms);
        let _me = this;
        _me.setState({
          loading: true,
        });
        Utils.sendAjax({
          url: '/rent/batchMeter/add',
          data: JSON.stringify(params),
          callback: function(result) {
            if (result.code == '200') {
              Message.success(result.message);
              _me.handleSearch();
              _me.setState({
                loading: false,
              });
              // _me.resetFieldArr(_me.state.setData);              
            } else {
              _me.setState({
                loading: false,
              });
              Message.error(result.message, 10);
            }
          }
        })
    }else{
      Message.error('刻度未抄表 或时间为空，请检查~',10);
    }
  },

  setFieldArr(str) {
    let ids = Utils.uniqueArr(this.state.ids);
    let newArr = [];
    ids.forEach((k) => {
      let arr = [];
      let newStr = {};
      let water = {};
      let elect = {};
      let natgas = {};
      for (let o in str) {
        let arr = o.split('-');
        let key = arr[0];
        if (arr[1] == 'w') {
          water[key] = str[o];
        } else if(arr[1] == 'e') {
          elect[key] = str[o];
        } else {
          natgas[key] = str[o];
        }
      }

      if (water.scale && water.scaleTime) {
        arr.push(water);
      }
      if (elect.scale && elect.scaleTime) {
        arr.push(elect);
      }
      if (natgas.scale && natgas.scaleTime) {
        arr.push(natgas);
      }
      newStr['meterList'] = arr;
      newStr['roomId'] = k;
      newArr.push(newStr);
    })
    return newArr;
  },

  showModal(param) {
    this.setState({
      visible: true,
      roomId: param
    });
  },

  handleCancel() {
    this.setState({
      visible: false,
    });
  },

  

  itemRender(data) {
    if (!data[0]) {
      return
    }
    let itemRender = [];
    data.forEach((list, k)=> {
      let wrapTr = (
        <tr className="table-wrap-tr" key={`tr-${list.tenementId}`}>
          <td colSpan="11">{list.address}</td>
        </tr>
      );
      itemRender.push(wrapTr);

      list.roomList.map((item, index)=> {
        let water = {};
        let elect = {};
        let natgas = {};
        water[`meterType-w-${item.roomId}`] = 1;
        water[`key`] = `meterType-w-${item.roomId}`;
        water[`name`] = `scale-w-${item.roomId}`;
        elect[`meterType-e-${item.roomId}`] = 2;
        elect[`key`] = `meterType-e-${item.roomId}`;
        elect[`name`] = `scale-e-${item.roomId}`;
        natgas[`meterType-n-${item.roomId}`] = 3;
        natgas[`key`] = `meterType-n-${item.roomId}`;
        natgas[`name`] = `scale-n-${item.roomId}`;
        let itemTr = (
          <tr key={`tr-${item.roomId}`}>
            <td>{item.roonName}</td>
            <td>{item.waterLastScale}<br/>{item.waterScaleTime ? `(${item.waterScaleTime})`: ''}</td>
            <td><InputNumber name={`scale-w-${item.roomId}`} defaultValue={item.waterLastScale} min={item.waterLastScale ? item.waterLastScale : 0} onChange={this.handleFiled.bind(this, water)} style={{width: 80}}/></td>
            
            <td><DatePicker disabledDate={this.disabledEndDate}  onChange={this.handleFiled.bind(this, `scaleTime-w-${item.roomId}`)} style={{width: 110}}/></td>
            
            <td>{item.electricLastScale}<br/>{item.electricScaleTime ? `(${item.electricScaleTime})`: ''}</td>
            <td><InputNumber  name={`scale-e-${item.roomId}`} defaultValue={item.electricLastScale} min={item.waterLastScale ? item.waterLastScale : 0} onChange={this.handleFiled.bind(this, elect)} style={{width: 80}}/></td>
            <td><DatePicker disabledDate={this.disabledEndDate} onChange={this.handleFiled.bind(this, `scaleTime-e-${item.roomId}`)} style={{width: 110}}/></td>
            <td>{item.natgasLastScale}<br/>{item.natgasScaleTime ? `(${item.natgasScaleTime})`: ''}</td>
            <td><InputNumber   name={`scale-n-${item.roomId}`} defaultValue={item.natgasLastScale} min={item.waterLastScale ? item.waterLastScale : 0} onChange={this.handleFiled.bind(this, natgas)} style={{width: 80}}/></td>
            <td><DatePicker disabledDate={this.disabledEndDate} onChange={this.handleFiled.bind(this, `scaleTime-n-${item.roomId}`)} style={{width: 110}}/></td>
            <td>
              <a href="javascript:;" onClick={this.showModal.bind(this, item.roomId)}>抄表记录</a>
            </td>
          </tr>
        )
        itemRender.push(itemTr);
      })
    })

    return itemRender;
  },

  render() {
    const { getFieldProps } = this.props.form;

    return (
      <div>
        <div className="search-bar" >
        <Row>
          <Col span={15}>
            <Form inline>
              <FormItem  label="房间名称">
                <Input {...getFieldProps('roomName') } placeholder="房间名称"/>
              </FormItem>
                 <FormItem  label="物业名称">
                <Input {...getFieldProps('tenementName') } placeholder="物业名称"/>
              </FormItem>
              <FormItem>
                <Button type="primary" onClick={this.handleSearch} style={{marginRight: 20}}>查询</Button>
                <Button type="default" onClick={this.handleReset} >重置</Button>
              </FormItem>
              
            </Form>
          </Col>
          <Col span={7}>

          </Col>
          <Col span={2}>
            <Button   type="primary" loading={this.state.loading} onClick={this.handleSubmit}>保存</Button>
          </Col>
        </Row>
          
          
          
        </div>

        <div className="ant-table ant-table-large ant-modify ">
          <table className="ant-table-body">
            <thead className="ant-table-thead">
              <tr>
                <th rowSpan="2" style={{width: 80}}>房间名称</th>
                <th colSpan="3">水表</th>
                <th colSpan="3">电表</th>
                <th colSpan="3">天然气表</th>
                <th rowSpan="2" style={{width: 80}}>操作</th>
              </tr>
              <tr>
                <th>上次刻度</th>
                <th>本月刻度</th>
                <th>抄表时间</th>
                <th>上次刻度</th>
                <th>本月刻度</th>
                <th>抄表时间</th>
                <th>上次刻度</th>
                <th>本月刻度</th>
                <th>抄表时间</th>
              </tr>
            </thead>
            <tbody>
              {this.state.dataBox}
            </tbody>
          </table>
          {this.state.data[0] ?
          <div className="box-page">
            <Pagination onChange={this.handlePageChange}
                        current={this.state.page.current} total={this.state.page.total} pageSize={this.state.page.pageSize} />
          </div>: null}
        </div>
        <BatchChargingModal visible={this.state.visible} roomId={this.state.roomId} callHide={this.handleCancel}/>
      </div>
    );
  }
});
List = Form.create()(List)
export default List